package com.nearbymap.maps;

import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.nearbymap.model.DirectionsResponse;
import com.nearbymap.model.XmlResponse;
import com.nearbymap.tooling.XmlService;

@Service
public class DirectionsService {
	
	@Autowired
	private XmlService xmlService;
	
	public URL getDirectionsUrl(String origin, String destination, String waypoints) {
		try {
			origin = URLEncoder.encode(origin, "UTF-8");
			destination = URLEncoder.encode(destination, "UTF-8");
			waypoints = URLEncoder.encode(waypoints, "UTF-8");
			StringBuffer urlBuffer = 
					new StringBuffer("http://maps.googleapis.com/maps/api/directions/xml?origin=").append(origin)
					.append("&destination=").append(destination);
			if(waypoints != null)
				urlBuffer.append("&waypoints=").append(waypoints);
			urlBuffer.append("&sensor=false");
			System.out.println("DirectionsUrl: " + urlBuffer.toString());
			URL directionsUrl = new URL(urlBuffer.toString());
			return directionsUrl;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			throw new RuntimeException(e.getMessage(), e);
		} catch (MalformedURLException e) {
			e.printStackTrace();
			throw new RuntimeException(e.getMessage(), e);
		}
	}

	public DirectionsResponse getDirectionsXml(String origin, String destination, String waypoints) {
		return new DirectionsResponse(xmlService.query(getDirectionsUrl(origin, destination, waypoints)));
	}

	public XmlResponse query(URL xmlServiceUrl) {
		return xmlService.query(xmlServiceUrl);
	}
}
